import {defineStore} from "pinia";
import {
  get_orderHistory,
  get_tradeHistory,
  delete_history,
  delete_allHistory} from "@/api/tradeApi.ts";

// 评估指标
export interface Evaluate {
  profit_rate: number
}

// 订单历史记录列表
export interface orderHistory {
  orderID: string
  code: string
  date_time: string
  strategy_name: string
  evaluate: Evaluate
}

export const useTradeStore = defineStore('tradeStore', () => {

  const orderHistoryList = ref<{
    orderID: string
    code: string
    date_time: string
    strategy_name: string
    profit_rate: number
  }[]>([])
  // 获得交易记录
  const tradeHistoryList = ref<{
    orderID: string
    date_time: string
    price: number
    signal: number
    profit_cash: number
    cash: number
    new_position: number
    total_position: number
  }[]>([])

  // 获得所有的订单记录
  const getOrderHistory = async () => {
    orderHistoryList.value = []
    const res = await get_orderHistory()
    if (res.code === 1){
      res.data.forEach((o: orderHistory) => {
        orderHistoryList.value.push({
          orderID: o['orderID'],
          code: o['code'],
          date_time: o['date_time'],
          strategy_name: o['strategy_name'],
          profit_rate: o.evaluate['profit_rate'], // 注意不要漏字段
        })
      })
      console.log(orderHistoryList.value)
    }
    return res.message
  }

  // 获得交易记录
  const getTradeHistory = async (orderID: string) => {
    tradeHistoryList.value = []
    const res = await get_tradeHistory(orderID)
    if (res.code === 1){
      tradeHistoryList.value = res.data
    }
    return res.message
  }

  // 删除记录
  const deleteHistory = async (orderID: string) => {
    const res = await delete_history(orderID)
    if (res.code === 1){
      tradeHistoryList.value = []
      await getOrderHistory()
    }
    return res.message
  }

  // 删除全部记录
  const deleteAllHistory = async () => {
    const res = await delete_allHistory()
    if (res.code === 1){
      tradeHistoryList.value = []
      orderHistoryList.value = []
    }
    return res.message
  }

  return{
    orderHistoryList,
    getOrderHistory,
    tradeHistoryList,
    getTradeHistory,
    deleteHistory,
    deleteAllHistory
  }
})
